/**
 * KindEditor 拖拽上传插件
 * author:ksc(http://blog.geekli.cn)
 * lastupdate:2014.1.23.3
 * 支持chrome、火狐最新版本
 */
KindEditor.plugin('dragDropUpload', function(K) {
    var editor = this,
        name = 'dragDropUpload',
        uploadJson = K.undef(editor.uploadJson, editor.basePath + 'php/upload_json.php');
    var dropbox='_dragdropbox';
    var fileList={};  
    //点击图标时执行
    var show_dialog=function(){
        var _dialog_html=[
                '<div id="'+dropbox+'" style="min-width:300px; height:300px;overflow:scroll;border:3px dashed silver; margin:5px;" >',
                '<div id="_upload_preview"></div>',
                '</div> '
                ].join('');
       
        var dialog = editor.createDialog({
            name : name, width : 500, height : 400, title : editor.lang(name), showMask:false,
            body : _dialog_html,
            yesBtn : {
                name : editor.lang('yes'),
                click : function(e) {
                    var _insertHtml=[];
                    
                    for(i in fileList){
                       if(typeof(fileList[i]) =='function'){
                            continue;
                       }
                       _insertHtml.push(insertImgHtml(i));
                    }
                    
                    editor.insertHtml(_insertHtml.join(''));
                    setTimeout(function() {
                        editor.hideDialog().focus();
                    }, 0);
                     
                }
            }
        });// createDialog end
        
        K.query('#'+dropbox).addEventListener('click',function(e){
            if(e.srcElement.className=='ddu-img'){
                var img=e.srcElement;
                console.log(img.attributes);
                editor.insertHtml(insertImgHtml(img.attributes['fid'].value));
            }
    
        }); 
        var op={
                'fileFieldName'	:'imgFile',
                'server'		: K.addParam(uploadJson, 'dir=image'),
                'onUpload'		:function(text,fid){
                     
                    var data=K.json(text);
                    data['fid']=fid;
                    console.log('服务器接口返回数据:',data)
                    fileList[fid]=data;

                }
                
            };   
        try{
            var dd=new DDU(dropbox,op);
        }catch(e){
            alert("只支持火狐和chrome");
        };
            

    };
    
 
    function insertImgHtml(fid){
        
        var _alt=K.query('#ke-ddu-item'+fid+' input').value;
        return '<img src="'+fileList[fid]['url']+'" alt="'+_alt+'" title="'+_alt+'"/> <br/>'
    }
    editor.clickToolbar(name, function() {
        show_dialog();
    });
});

 
var DDU = function(container,op) {
	this.options	=(typeof(op)=='undefined')?{}:op;
	this.container	=document.getElementById(container);
	this.server		=op.server;
	this.fileFieldName=op.fileFieldName;
	this.onUpload	=this.getP('onUpload',function(){});//上传成功后的回调函数
	this.onRead 	=this.getP('onRead',function(){});//上传成功后的回调函数
	this.fileIndex	=0;//容器中的文件索引
	this.files		= new Array();//容器中的文件
	
 	this.init();
}
DDU.prototype={
	init:function(){
		this._init();
		var box=this.container;
		var self=this;
	 
		/*
        box.addEventListener("dragenter", function(e){   
			box.style.borderColor = 'gray';   
			box.style.backgroundColor = 'white';   
		}, false);   
		box.addEventListener("dragleave", function(e){   
			box.style.backgroundColor = 'transparent';   
		}, false);  */ 
		box.addEventListener("dragenter", function(e){ e.stopPropagation();  e.preventDefault(); }, false);   
		box.addEventListener("dragover" , function(e){ e.stopPropagation();  e.preventDefault(); }, false);   
		box.addEventListener("drop", function(e){   e.stopPropagation();    e.preventDefault();   
				 
			self.handleFiles(e.dataTransfer.files);           
		
		}, false);
	},
	//处理文件
	handleFiles : function(files) {   
		for (var i = 0; i < files.length; i++) {
			var file = files[i]; 
			if (!file.type.match(/image*/)) {
				continue;   
			}   	
			//预览图片
            var fid=this.fileIndex++;    
			this.preview_file(file,fid);
			//上传图片
			this.upload_file(file,fid)
		}	
    },
	//预览图片
	preview_file : function(file,fid){
		
		this.files[fid]=file;
		var self=this;
		var s='<div id="ke-ddu-item'+fid+'" class="ke-ddu-item" style="overflow:hidden;border-bottom:1px solid #DDD;  margin:2px 5px; padding:5px;" >';
			
			//s+='<button id="bt_del_'+fid+'"></button>';
			//s+='<input type="checkbox" name="" value="'+fid+'" /><br> ';
		var rd=new FileReader();
			rd.onload=function(e){
					 
                s+='<img src="'+this.result+'" fid="'+fid+'" class="ddu-img" style="float:left;margin-right: 10px;" width="120" />';
                s+="<span>"+file.name+"</span>";
                s+='<br/><label for="">alt:</label><input type="text" class="ke-input-text" value=""/>';
                s+='</div>';
                self.container.innerHTML+=s;
                 
            }
			rd.readAsDataURL(file);  
			 
			
	},	
	//上传文件
	upload_file : function (file,fid){
        var self=this;
        var reader = new FileReader(); 
		reader.readAsBinaryString(file);
		 
		reader.onloadend = function(){
			//bug(this.readyState); // 这个时候 应该是 2
			var fileData=this.result;
			var CRLF="\r\n";
			var xhr = new XMLHttpRequest();   
			xhr.open('post', self.server, false);
			//xhr.onreadystatechange=function(){};
			var boundary='----ksc-'+self.getBoundary()+'----';
            
			// simulate a file MIME POST request.     
			xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary);
			//xhr.setRequestHeader("Content-Length", file.size);     
			var body = '';     
			body += '--' + boundary + CRLF;
			body += 'Content-Disposition: form-data; name="'+self.fileFieldName+'"; filename="' + file.name + '"'+CRLF;     
			body += "Content-Type: "+file.type+CRLF+CRLF;     
			body += fileData + CRLF;     
			body += "--" + boundary + "--"+CRLF;     
			xhr.sendAsBinary(body);
			self.onUpload(xhr.responseText,fid); 
			
			
		}
	},
	//兼容性处理
	_init:function(){
		if(typeof(XMLHttpRequest.prototype.sendAsBinary)=='undefined'){
			XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
				function byteValue(x) {
					return x.charCodeAt(0) & 0xff;
				}
				var ords = Array.prototype.map.call(datastr, byteValue);
				var ui8a = new Uint8Array(ords);
				this.send(ui8a.buffer);
			}
		}//end if
	
	},
    getBoundary:function(){
        var max = 9007199254740992;
        var dec = Math.random() * max;
        return hex = dec.toString(36);
    }
	,
	getP:function(t,def){
		return typeof(this.options[t])=='undefined'?def:this.options[t];
	}
	
};